<?php
/* lib by tj 2013-4-4 */
class tx_mfwcshoolinfos_lib {  

	var $db;
	var $pObj;
	
	function __construct(&$pObj) {
	
		$this->db = &$GLOBALS['TYPO3_DB'];
		
		$this->pObj = &$pObj;
		$this->pObj->extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$this->pObj->extKey]);
		$this->pObj->thumb = array(
			'list' => array('maxH' => 20,'maxW' => 100),
			'edit' => array('maxH' => 300,'maxW' => 300)
		);
		include(t3lib_extMgm::extPath($this->pObj->extKey).'ext_tables.php');
	}
	
	
	
	/**
	 * 提醒框
	 */
	function notificationBox($urlList,$urlAdd){
		
		$content = '
			<div class="alert alert-success alert-block">
				<h4 class="alert-heading">保存成功!</h4>
				<a href="'.$urlAdd.'" target="_self">继续添加</a>&nbsp;&nbsp;
				<a href="'.$urlList.'" target="_self">返回列表</a>
			</div>		
		';
		return $content;
	}
	
	
	/**
	 *  更新成功信息
	 *  @$success  //true 成功  //false 失败
	 *  @$message //提示信息
	 */
	function notificationMSG($success,$message){
		
		
		if(empty($message)) return false;
		
		if($success)
			$this->pObj->msg = '<div class="alert alert-success">
							<button data-dismiss="alert" class="close">×</button>
							<strong>'.$message.'</strong></div>';
							
		else $this->pObj->msg = '<div class="alert alert-error">
							<button data-dismiss="alert" class="close">×</button>
							<strong>'.$message.'</strong>
						</div>';

	}
	
	
	
	/**
	 * 按钮
	 * $uid 记录ID
	 * $btn array 
	 *{ title => 'abc'
	 *  pid => 123
	 *  items{
	 *   'sid' => 2011001,'cmd'=>'preview'
	 *}}
	 */
	function actionButtons($uid,$btn = array()){
	
		$content = '';
		if($this->pObj->flex['buttons']){
		
			$items = explode(',',$this->pObj->flex['buttons']);
			foreach($items as $item){
				switch($item){
				
					case 'view';
						$content .= '&nbsp;<button type="button" class="btn btn-mini" 
								onclick=\'javascript:window.open("/'.$this->selfT3Url(array('cmd'=>'preview','uid'=>$uid,'back'=>$this->pObj->backurl),$this->pObj->flex['detailpid']).'","_blank")\'
							><i class="icon-eye-open"></i> 查看</button>';
						break;
						
					case 'edit';
						$edit_pageid = $this->pObj->flex['editpid'];
						if(t3lib_div::inList($this->pObj->userData['usergroup'],$this->pObj->extConf['supervisemgr']) && $this->pObj->flex['schoolAddPid']){
							$edit_pageid = $this->pObj->flex['schoolAddPid'];
						}
						
						$content .= '&nbsp;<button type="button" class="btn btn-primary btn-mini" 
								onclick=\'javascript:window.open("/'.$this->selfT3Url(array('uid'=>$uid,'back'=>$this->pObj->backurl),$edit_pageid).'","_blank")\'
							><i class="icon-pencil icon-white"></i> 编辑</button>';
						break;

						
					case 'audit';
						$content .= '
							&nbsp;<div class="btn-group">
									  <button class="btn btn-danger  btn-mini dropdown-toggle" data-toggle="dropdown"><i class="icon-white icon-ok-circle"></i>审核<span class="caret"></span></button>
									  <ul class="dropdown-menu">
										<li><a onclick="javascript:listAudit(jQuery(this)); return false;" href="/'.$this->selfT3Url(array('cmd'=>'audit','val'=>'1','uid'=>$uid,'back'=>$this->pObj->backurl),$GLOBALS['TSFE']->id).'">审核通过</a></li>
										<li><a onclick="javascript:listAudit(jQuery(this));  return false;" href="/'.$this->selfT3Url(array('cmd'=>'audit','val'=>'0','uid'=>$uid,'back'=>$this->pObj->backurl),$GLOBALS['TSFE']->id).'">取消审核</a></li>
									  </ul>
							</div>
						';
						break;
						
					case 'delete';
						$content .= '&nbsp;<button class="btn btn-inverse btn-mini" 
							onclick="javascript:ajaxDel(jQuery(this));"
							href="'.$this->selfT3Url(array('cmd'=>'del','uid'=>$uid,'back'=>$this->pObj->backurl),$GLOBALS['TSFE']->id).'"><i class="icon-white icon-remove"></i> 删除</button>';
						break;
						
					case 'back';
					
						$content .= $this->closeButton();
						//$content .= '&nbsp;<button type="button" class="btn" 
						//		onclick=\'javascript:location.href="/'.urldecode($this->pObj->get['back']).'"\'
						//	><i class="icon-list-alt"></i> 返回</button>';
						break;
				}
				
			}
			
			return $content;
			
		}else if(!empty($btn) && $uid == 0){
		
			$urlVars = $btn['items'];
			$urlVars['back'] = $this->pObj->backurl;
			return '<button type="button" class="btn btn-mini" 
								onclick=\'javascript:window.open("/'.$this->selfT3Url($urlVars,$btn['pid']).'","_blank")\'
							><i class="icon-eye-open"></i>'.$btn['title'].'</button>';
			
		}
	}
	
	
	/**
	 * 分页选择器
	 */
	function pagesizeSelect(){
		
		$content = '';
		$data = array('1'=>'1','10'=>'10','20'=>'20','30'=>'30');
		$default = $this->pObj->get['pagesize'] ? $this->pObj->get['pagesize'] : '20';
		if(!empty($data)){
			$content .= '<select class="urljump">';
			foreach($data as $k =>$v){
				$select = ''; if($v == $default) $select = 'selected="selected"';
				$piVars = $this->pObj->get;
				$piVars['pagesize'] = $v;
				$content .= '<option '.$select.' value="'.$this->selfT3Url($piVars,$GLOBALS['TSFE']->id).'">'.$k.'</option>';
			}
			$content .= '</select>';
		}
		return $content;
	}
	
	
	
	
	
	/**
	 * 城市信息
	 */
	function  ajaxCityOptions(){
		
		if($this->pObj->get['ajaxcity']){
			
			$content = '';
			if($this->pObj->get['zone']){
				
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tx_mfwcshoolinfos_city','deleted=0 AND hidden=0 AND parent_id='.$this->pObj->get['zone']);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)){
					$content .= '<option value="'.$row['uid'].'">'.$row['title'].'</option>';
				}
				$GLOBALS['TYPO3_DB']->sql_free_result($res);
			
			}else if($this->pObj->get['city']){
				
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title','tx_mfwcshoolinfos_county','deleted=0 AND hidden=0 AND parent_id='.$this->pObj->get['city']);
				while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)){
					$content .= '<option value="'.$row['uid'].'">'.$row['title'].'</option>';
				}
				$GLOBALS['TYPO3_DB']->sql_free_result($res);
			
			}
			exit(json_encode($content));
		}
	}
	
	
	
	/**
	 * 得到页码信息
	 */
	function getPageLimit(){
	
	
		$pagesize = $this->pObj->get['pagesize'] ? $this->pObj->get['pagesize'] : '20';
		$page = $this->pObj->get['page'] ? $this->pObj->get['page'] : 0;
		$limit = ( $page * $pagesize ).','.$pagesize;
		return $limit;
	}
	
	/**
	 * 分页器
	 */
	function pageBrowser($total) {
	
		$pagesize = $this->pObj->get['pagesize'] ? $this->pObj->get['pagesize'] : '20';
		$numberOfPages = ceil($total / $pagesize);
		
		// Get default configuration
		$conf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_pagebrowse_pi1.'];
		// Modify this configuration
		$conf = array_merge ($conf,array(
			'pageParameterName' => $this->pObj->prefixId . '|page',
			'numberOfPages' => $numberOfPages,
		));
		// Get page browser
		$cObj = t3lib_div::makeInstance('tslib_cObj');
		/* @var $cObj tslib_cObj */
		$cObj->start(array(), '');
		return $cObj->cObjGetSingle('USER', $conf);
	}
	
	
	
	/**
	 * 文件上传处理
	 */
	function fileUpload($file,$config,$imgs){
	
		$val = $imgs;
		$files=$_FILES[$this->pObj->prefixId];
		if($files['name'][$file]){
			if(is_array($files['name'][$file])){
				foreach($files['name'][$file] as $k => $v){
					$filename = $this->singleFileUpload($file,$config,$k);
					if($filename){
						if($imgs[$k]){
							unlink($config['uploadfolder'].'/'.$imgs[$k]);
						}
						$imgs[$k] = $filename;
					}
				}
				
				if(!empty($imgs)){
					foreach($imgs as $img){
						if(!empty($img)){
							if(!empty($val)) $val .= ','.$img;
							else $val = $img;
						}
					}
				}
			}else{ //只有一个附件
				
				$files=$_FILES[$this->pObj->prefixId];
				if(is_uploaded_file($files['tmp_name'][$file])){
					if($files['size'][$file]<=$config['max_size']*1024){
					
						$fI=t3lib_div::split_fileref($files['name'][$file]);
						if(t3lib_div::inList($config['allowed'],$fI['fileext']) && t3lib_div::verifyFilenameAgainstDenyPattern($files['name'][$file])){
						
							$filename= date('Ymd').strtotime('now').rand(0,100).'.'.$fI['fileext'];
							t3lib_div::upload_copy_move($files['tmp_name'][$file],$config['uploadfolder'].'/'.$filename);
							return $filename;
						}else{
							$this->pObj->errors[$file]='上传文件格式错误，只允许上传'.$config['allowed'].'格式的文件';
						}
					}else{
						$this->pObj->errors[$file]= '上传文件超出最大值 '.$config['max_size'].'KB';
					}
				}
			}
		}	
		
		return $val;
	}
	/**
	 * 单个文件上传处理
	 */
	function singleFileUpload($file,$config,$k){
		$files=$_FILES[$this->pObj->prefixId];
		if(is_uploaded_file($files['tmp_name'][$file][$k])){
			if($files['size'][$file][$k]<=$config['max_size']*1024){
			
				$fI=t3lib_div::split_fileref($files['name'][$file][$k]);
				if(t3lib_div::inList($config['allowed'],$fI['fileext']) && t3lib_div::verifyFilenameAgainstDenyPattern($files['name'][$file])){
				
					$filename= date('Ymd').strtotime('now').rand(0,100).'.'.$fI['fileext'];
					t3lib_div::upload_copy_move($files['tmp_name'][$file][$k],$config['uploadfolder'].'/'.$filename);
					return $filename;
				}else{
					$this->pObj->errors[$file][$k]='上传文件格式错误，只允许上传'.$config['allowed'].'格式的文件';
				}
			}else{
				$this->pObj->errors[$file][$k]= '上传文件超出最大值 '.$config['max_size'].'KB';
			}
		}
	}
	
	
	function getMarkerNames($template,$type){
	
		preg_match_all('/###([_a-zA-Z0-9]+)_'.$type.'###/',$template,$erg);
		return($erg[1]);
	}
	


	function getMarker($fields,$table,$mk,$default = array(),$disabled=false){	
	
		$marker = array();
		foreach($fields as $key){
			$value = @$default[$key];
			$marker['###'.$key.'_'.$mk.'###'] = $this->getSingleMarker($key,$table,$value,$disabled);
		}		
		return $marker;
	}
	
	
	/**
	 * 市，区县 下拉选择
	 */
	function cityAndCountySelecter($file,$foreign_table,$parent_id,$value=''){

		$refresh = '';
		$where = 'deleted = 0 AND hidden = 0 AND parent_id='.$parent_id;
		
		switch($file){
			case 'zone':
				$where = 'deleted = 0 AND hidden = 0';
				$refresh = ' refresh';
				break;
			case 'city':
				$refresh = ' refresh';
				break;
		}
		$name=$this->pObj->prefixId.'['.$file.']';
		$content = '<select id="'.$file.'" class="nopretty easyui-combobox select2 '.$refresh.'" name="'.$name.'"  '.$disabled.' style="min-width:300px;" >';
		$content .= '<option value=""></option>';

		$res = $this->db->exec_SELECTquery('uid,title', $foreign_table,$where);
		while ($row = $this->db->sql_fetch_assoc($res)) {
			$content .= '<option value="'.$row['uid'].'"'.(t3lib_div::inList($value,$row['uid']) ? ' selected="selected"' : '').'>'.$row['title'].'</option>';
		}
		$content .= '</select>';
		return $content;
	}

	/** 
	 * 单个字段 表单获取
	 */
	function getSingleMarker($file,$table, $value = '',$dis=false,$whereplus = '',$use_schoolid = false){
	
		$m='';
		$pattern='';
		$disabled = '';
		if($dis) $disabled = ' disabled="disabled" ';
		
		$this->loadTCA($table);
		$name=$this->pObj->prefixId.'['.$file.']';
		$config=$GLOBALS['TCA'][$table]['columns'][$file]['config'];
			switch($config['type']){
				case 'check':
					$i = 0;
					if($config['items']){
						foreach($config['items'] as $item){
							$m .= '<input name="'.$name.'['.$i.']" '.$disabled.' type="checkbox" value="'.$item[1].'"'.(t3lib_div::inList($value,$item[1]) ? ' checked="checked"' : '').' />'.$item[0];
							$i++;
						}
					}else{
						$m .= '<input name="'.$name.'['.$i.']" '.$disabled.' type="checkbox" value="1"'.(t3lib_div::inList($value,'1') ? ' checked="checked"' : '').' />';
					}
					break;
				case 'group':
					if($config['internal_type']=='file'){
						//同时上传多个文件
						if(isset($config['maxitems']) && $config['maxitems'] > 1){
						
							
							$m = '<div class="my_prop_img">';
							$img = explode(',',$value);
							for($i=0; $i < $config['maxitems']; $i++){
								$m .= '<div class="item">';
								//if(is_file($config['uploadfolder'].'/'.$img[$i])) $m .= $this->getImageThumb($this->pObj->thumb['edit'],$config['uploadfolder'].'/'.$img[$i]).'<br />';
								$m .= $this->showFileLink($config['uploadfolder'].'/'.$img[$i],'edit').'<br />';
								
								$m .= '<input name="'.$name.'['.$i.']"  value="'.$img[$i].'" type="hidden" />';
								$m .= '<input name="'.$name.'['.$i.']"  '.$disabled.' type="file" />';
								$m .= '</div>';
								if(isset($this->pObj->errors[$file]) && $this->pObj->errors[$file][$i]){
									$m.='<span class="error">'.$this->pObj->errors[$file][$i].'</span>';
								}
							}	
							$m .= '</div>';
						}else{
						
							//if(is_file($config['uploadfolder'].'/'.$value)) $m .= $this->getImageThumb($this->pObj->thumb['edit'],$config['uploadfolder'].'/'.$value).'<br />';
							$m .= $this->showFileLink($config['uploadfolder'].'/'.$value,'edit').'<br />';
							$m .= '<input name="'.$name.'"  value="'.$value.'" type="hidden" />';
							$m.='<input name="'.$name.'"  '.$disabled.' type="file" />';
						}
					}
					break;
				case 'input':
					if(t3lib_div::inList($config['eval'],'password')){
					
						$m='<input id="'.$file.'" name="'.$name.'[]" type="password"';	
					}else if(t3lib_div::inList($config['eval'],'datetime') || t3lib_div::inList($config['eval'],'date')){
					
						if(!$value) $value = '';
						$date = explode("-", $value); 
						if(!checkdate($date[1], $date[2], $date[0])) $value = date('Y-m-d',$value); 
						$m='<input id="'.$file.'" class="datepicker" name="'.$name.'" type="text" value="'.$value.'"';		
					}else if(t3lib_div::inList($config['eval'],'hidden')){
					
						$m='<input id="hidden_id" name="'.$name.'" type="hidden" value="'.$value.'"';
					}else{
					
						$m='<input id="'.$file.'" name="'.$name.'" type="text" value="'.$value.'"';
					}
					if($config['max']) $m.=' maxlength="'.$config['max'].'"';
						$m.=' '.$disabled.'/>';
					//$m.='<span id="'.$file.'Tip" style="width:200px;display:inline"></span>';
					break;
				case 'radio':
					$i=1;
					foreach($config['items'] as $item){
						$m.='<label><input  name="'.$name.'" type="radio"  '.$disabled.' value="'.$item[1].'"'.($value==$item[1] ? ' checked="checked"' : '').' />'.$this->getTcaTranslate($item[0]).'</label>&nbsp;';
						$i++;
					}
					//$m.='<span id="'.$file.'Tip" style="width:200px;display:inline"></span>';
					break;
				case 'select':
				
					$options = '';
					if($config['item_title']){
						foreach($config['item_title'] as $item_title){
							$options.='<optgroup label="'.$item_title[0].'" style=" ">';
							foreach($config['items'] as $item){
								if($item[2] == $item_title[1]){
									if($value){
										$options.='<option value="'.$item[1].'"'.(t3lib_div::inList($value,$item[1]) ? ' selected="selected"' : '').'>'.$this->getTcaTranslate($item[0]).'</option>';
									}else{
										$options.='<option value="'.$item[1].'"'.(t3lib_div::inList($config['default'],$item[1]) ? ' selected="selected"' : '').'>'.$this->getTcaTranslate($item[0]).'</option>';
									}
								}				
							}
							$options.='</optgroup>';
						}
					}else{
						foreach($config['items'] as $item){
							if($value){
								$options.='<option value="'.$item[1].'"'.(t3lib_div::inList($value,$item[1]) ? ' selected="selected"' : '').'>'.$this->getTcaTranslate($item[0]).'</option>';
							}else{
								$options.='<option value="'.$item[1].'"'.(t3lib_div::inList($config['default'],$item[1]) ? ' selected="selected"' : '').'>'.$this->getTcaTranslate($item[0]).'</option>';
							}		
						}
					}
						
					if($config['foreign_table']){
					
						$this->loadTCA($config['foreign_table']);
						
						if (preg_match ("/###REC_FIELD_\w+###/i",$config['foreign_table_where'])){ //如果条件带判断，删除条件
							$config['foreign_table_where'] = '';
						}
						
						$where = ' WHERE deleted=0 AND hidden=0  '.$whereplus.' '.$config['foreign_table_where'];
						
						
						if($use_schoolid == true){
							$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'] = 'tx_mfwcshoolinfos_id';
						}
						
						if($config['foreign_table'] == 'fe_users'){
							$where = ' WHERE deleted=0 AND disable=0 '.$whereplus.' '.$config['foreign_table_where'];
						}
						
						//debug('SELECT uid,'.$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'].' FROM '.$config['foreign_table'].' '.$where,'sql');
						$res=$this->db->sql_query('SELECT uid,'.$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'].' FROM '.$config['foreign_table'].' '.$where);
						while($row=$this->db->sql_fetch_assoc($res)){
							$options.='<option value="'.$row['uid'].'"'.(t3lib_div::inList($value,$row['uid']) ? ' selected="selected"' : '').'>'.$row[$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label']].'</option>';
						}
					}
					if(t3lib_div::inList('tx_mfwcshoolinfos_volunteer',$file))
						$m='<select id="'.$file.'" class="nopretty easyui-combobox search select2" name="'.$name.'"  '.$disabled.' style="min-width:300px;" >'.$options.'</select>';
					else 
						$m='<select id="'.$file.'" class="nopretty easyui-combobox select2" name="'.$name.'"  '.$disabled.' style="min-width:300px;" >'.$options.'</select>';
					//$m.='<span id="'.$file.'Tip" style="width:200px;display:inline"></span>';
					break;
				case 'text':
					$m='<textarea id="'.$file.'" class="kindeitor" name="'.$name.'" cols = '.$config['cols'].' rows = '.$config['rows'].' '.$disabled.' >'.$value.'</textarea>';
					//$m.='<span id="'.$file.'Tip" style="width:200px;display:inline"></span>';
					break;
		}
		if($this->pObj->errors[$file] && !is_array($this->pObj->errors[$file])) $m.='<span class="error">'.$this->pObj->errors[$file].'</span>';
		return $m;
	}
	
	
	/**
	 * 表单数据处理
	 */
	function processCheck($data,$table,$requid,$uniques = ''){
	
		$result = array();
		$this->loadTCA($table);
		foreach($data as $key => $value){
			if(empty($key)) continue;
			$config=$GLOBALS['TCA'][$table]['columns'][$key]['config'];
			//debug($config,'$config');
			switch($config['type']){
				case 'group':
					if($config['internal_type']=='file'){
						$result[$key] = $this->fileUpload($key,$config,$value);
						if(!isset($this->pObj->errors[$key]) && t3lib_div::inList($requid,$key) && empty($result[$key])){
							$this->pObj->errors[$key] = '必填项，不能为空';
						}
					
					}
				break;
				case 'check':
					$result[$key] = array_sum($value);
					break;
					
				default:
				
                    if($data['uid']) $uWhere = 'uid != '.$data['uid'].' AND '.$key.'='.$value;
                    else $uWhere = $key.'='.$value;
       
					if(t3lib_div::inList($requid,$key) && empty($value)){
                        $this->pObj->errors[$key] = '必填项，不能为空';
					}else  if(t3lib_div::inList($uniques,$key) && $this->db->exec_SELECTcountRows('uid',$table,$uWhere)){
                        $this->pObj->errors[$key] = '数据已存在，不能再增加';
					}else{
						$result[$key]=$value;
						if(t3lib_div::inList($config['eval'],'datetime') || t3lib_div::inList($config['eval'],'date')) $result[$key]= strtotime($value);
						if(t3lib_div::inList($config['eval'],'password')){
							$password = tx_mfwcshoolinfos_utils::generatePassword($value);
							$result[$key]= $password['encrypted'];
						}
					}
					break;
			}
		}
		
		if($this->pObj->errors){
			$this->pObj->msg = '
				<div class="alert alert-error">
					<button data-dismiss="alert" class="close">×</button>
					部分数据录入错误，请检查后重新提交
				</div>';
			
		}else{
			return $result;
		}
	}
    
	
	
	/**
	 * 根据字段判断是否有关联的外表，及外表字段
	 * @param $file string 字段名
	 * @param $table string 表名
	 * @return array()
	 */
	function getForeignFiled($file,$table){

		$data = array(
			'filed' => $file,
			'table' => $table,
		);
		
		$this->loadTCA($table);
		$config=$GLOBALS['TCA'][$table]['columns'][$file]['config'];
		if($config['type'] == 'select' && $config['foreign_table']){
			
			$asTableLink = $asTable = $config['foreign_table'];
			if($config['foreign_table'] == $table){
				$asTable = $table . uniqid('_join');
				$asTableLink = $table.' AS '.$asTable;
			}
			
			$data['foreign_filed'] = $GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'];
			$data['foreign_table'] = $asTable;
			$data['as_table'] = $asTableLink;
			$data['where'] = 'IF('.$table.'.'.$file.' > 0, '.$table.'.'.$file.'='.$asTable.'.uid'.',1=1)';
		}
		
		return $data;
	}
	
	
	
	function getMarkerInfo($files,$table,$mk,$data)
	{
		$marker = array();
		foreach($files as $f){
			$marker['###'.$f.'_'.$mk.'###'] = $this->getSingleMarkerInfo($f,$table,$data[$f]);
		}
		return $marker;
	}

	/**
	 * @param $file 字段名
	 * @param $table 表名
	 * @param $value 默认值
	 */
	function getSingleMarkerInfo($file,$table,$value)
	{
		$m = '';
		$this->loadTCA($table);
		$config=$GLOBALS['TCA'][$table]['columns'][$file]['config'];
		
		//debug($config,'$config');
		
		if(!$config) return $value;
		if($config['type'] == 'user') $config=$GLOBALS['TCA'][$table]['columns'][$file]['org_conf'];

		switch($config['type']){
				case 'group':
					if($config['internal_type']=='file'){
						if(isset($config['maxitems']) && $config['maxitems'] > 1){
							$m = '';
							$files = explode(',',$value);
							for($i=0; $i < $config['maxitems']; $i++){
								$m .= $this->showFileLink($config['uploadfolder'].'/'.$files[$i],'list');
								return $m;
							}	
						}else{
						
							return $this->showFileLink($config['uploadfolder'].'/'.$value,'list');
						}
					}
					break;
					
				case 'select':
						
						if($config['items']){
							foreach($config['items'] as $item){
								if($value == $item[1]) return $this->getTcaTranslate($item[0]);
							}
						}
						
						if($config['foreign_table']){
						
							$this->loadTCA($config['foreign_table']);
							$where = ' WHERE deleted=0 AND hidden=0  AND uid = '.$value;
							if($config['foreign_table'] == 'fe_users') $where = ' WHERE deleted=0 AND disable=0 AND uid = '.$value;
							$res=$this->db->sql_query('SELECT uid,'.$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'].' FROM '.$config['foreign_table'].' '.$where);			
							$row=$this->db->sql_fetch_assoc($res);
							return $row[$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label']];
						}
						
					return $value;
					break;
				case 'inline':
					
					$this->loadTCA($config['foreign_table']);
					$where = ' WHERE deleted=0 AND hidden=0  AND uid in('.$value.')';
					if($config['foreign_table'] == 'fe_users') $where = ' WHERE deleted=0 AND disable=0 AND uid = '.$value;
					$res=$this->db->sql_query('SELECT uid,'.$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label'].' FROM '.$config['foreign_table'].' '.$where);			
					$row=$this->db->sql_fetch_assoc($res);
					return $row[$GLOBALS['TCA'][$config['foreign_table']]['ctrl']['label']];
					break;
					
				case 'radio':
					if($config['items']){
						foreach($config['items'] as $item){
							if($value == $item[1]){
								return $this->getTcaTranslate($item[0]);
							}
						}
					}
					return $value;
					break;
					
				case 'check':
					if($value) return '是';
					else return '否';
					break;
					
				case 'input':
				
					if(t3lib_div::inList($config['eval'],'datetime') || t3lib_div::inList($config['eval'],'date')){
						if($value) return date('Y-m-d',$value);
						return '';
					}
					return $value;
					break;
					
				default:
					return $value;
		}
	}
	
	
	/**
	 * 显示文件链接
	 * 图片显示缩略图
	 * @param $filepath 文件地址
	 * @param $display 视图类型， 存在对应的TS配置
	 * @return string html
	 */
	function showFileLink($filepath,$display){
		
		if(is_file($filepath)){
			if(t3lib_div::inList('gif,jpg,jpeg,tif,tiff,bmp,pcx,tga,png,pdf,ai',pathinfo($filepath,PATHINFO_EXTENSION)))
				return $this->getImageThumb($this->pObj->thumb[$display],$filepath);
			else 
				return '<a href="'.$filepath.'">查看</a>';
		}
	}
	
	
	function getFlexLabel($filed){
	
		$content = $filed['label'];
		if($filed['required']) $content .= '<span class="error">*</span>';
		
		return $content;
	}

	/**
	 * 获取表单标签
	 */
	function getMarkerDesc($fields,$table,$requids){
	
		//debug($fields,'$fields');
		$marker = array();
		foreach($fields as $f){
			$requid = t3lib_div::inList($requids,$f);
			$marker[] = $this->getSingleDesc($f,$table,$requid);
		}
		return $marker;
	}

	/**
	 * 获取 表单标签
	 */
	function getSingleDesc($file,$table,$requid = false){
		$this->loadTCA($table);
		$label=$GLOBALS['TCA'][$table]['columns'][$file]['label'];
		$name = $this->getTcaTranslate($label);
		if($requid) $name .= '<font color="#FF0000">*</font>';
		return $name;
	}
	
	
	/**
	 * 获取TCA标签多语言设置
	 */
	function getTcaTranslate($label){
		
		$pos=strrpos($label,':');
		$file=t3lib_div::getFileAbsFileName(substr($label,4,$pos-4));

		if(!isset($lang[$file])){
			if(substr($file,-3)=='php') $lang[$file]= \TYPO3\CMS\Core\Utility\GeneralUtility::readLLfile($file,'ch');
			else $lang[$file]=  \TYPO3\CMS\Core\Utility\GeneralUtility::readLLfile($file,$GLOBALS['LANG']->lang);

		}
	
		$name=$lang[$file][$GLOBALS['TSFE']->lang][substr($label,$pos+1)];
		if(empty($name)){
			$name=$lang[$file]['default'][substr($label,$pos+1)];
		}
		
		$name = $this->processNameArray($name);
		if(substr($name,-1)==':') $name=substr($name,0,-1);
		
		if(!empty($name)) return $name;
		return $label;
	}	
	
	
	function processNameArray($name){
		if(is_array($name)){
			foreach($name as $v){
				return $this->processNameArray($v);
			}
		}
		return $name;
	}
	
	/**
	 * 缩略图 大小设置
	 * 原始图片所在位置
	 * 是否显示图片链接
	 * @return string
	 */
	function getImageThumb($conf,$file,$link=true){		
		$picConf = array();
		$picConf['image.']['file'] = $file;
		$picConf['image.']['file.']['maxH'] = intval($conf['maxH']);
		$picConf['image.']['file.']['maxW'] = intval($conf['maxW']);
		$result = t3lib_div::makeInstance('tslib_cObj')->IMAGE($picConf['image.']);		
		if($link){	
			if (file_exists(t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT').'/'.$file)) {
				$imgdim = getimagesize(t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT').'/'.$file);
			}
			if(!$imgdim){
				$imgdim = array(800,600);
			}
			$file = '/'.$file;
			$result = '<a href="javascript:;" rel="'.$file.'" class="preview thumbnail" onclick="javascript:window.open(\''.$file.'\', \'图片查看\', \'width='.$imgdim[0].',height='.$imgdim[1].'\');">'.$result.'</a>';
		}
		return $result;
	}

	
	/**
	 * 得到格式化的URL
	 */
	function getUrlLink($url){
		
		if(!empty($url)){
			if (preg_match ('/^http:\/\//',$url) || preg_match ('/^https:\/\//',$url)) {
			}else{
				$url = 'http://'.$url;
			}
			
			return '<a href="'.$url.'" target="_blank">'.$url.'</a>';
		}
	}
	
	
	/**
	 * LOAD TCA
	 */
	function loadTCA($table){
		t3lib_div::loadTCA($table);
	}
	

	
	function delData($tablename='', $uids='') {
		if($tablename && $uids) {
			$post['deleted'] = 1;
			$res=$this->db->exec_UPDATEquery($tablename, '`uid` IN ('.$uids.')', $post); 
			return $res!==false;
		}
		return false;
	}
	
	
	function num($str) {
		return intval($str);
	}
	
	

	
	/**
	* get excel data 
	*/
	public function getExcelData($file) {

		require_once(t3lib_extMgm::extPath("phpexcel_library")."sv1/class.tx_phpexcellibrary_sv1.php");
		$PHPExcelSV = t3lib_div::makeInstance("tx_phpexcellibrary_sv1");
		$PHPExcelSV->init();
		//$objPHPExcel = new PHPExcel();
	
		/**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
		$PHPReader = new PHPExcel_Reader_Excel2007(); 
		if(!$PHPReader->canRead($file)){ 
			$PHPReader = new PHPExcel_Reader_Excel5(); 
			if(!$PHPReader->canRead($file)){ 
				echo 'no Excel'; 
				return ; 
			} 
		} 
		
		$objPHPExcel = $PHPReader->load($file); 
		$temp = $objPHPExcel->getSheet(0)->toArray(NULL,TRUE,TRUE);
		array_shift($temp);
		return $temp;
	} 
	
	/**
	* Encrypts the password for secure storage
	*
	* @param	string	$password: password to encrypt
	* @return	string	encrypted password
	*/
	function encryptPassword ($password) {
 
		$encryptedPassword = $password;
		if ($password !== '') {
			if (t3lib_extMgm::isLoaded('saltedpasswords') && tx_saltedpasswords_div::isUsageEnabled('FE')) { //salted password
				$objSalt = tx_saltedpasswords_salts_factory::getSaltingInstance(NULL);
				if (is_object($objSalt)) {
					$encryptedPassword = $objSalt->getHashedPassword($password);
				}
			}
		}
		return $encryptedPassword;
	}
	
	/**
	 * FLEXFORM 数据
	 */
	function flexfromConfiguration() {
	
		$flexConf = array();
		//lle Tabs der Flexformkonfiguration durchgehn.
		if (is_array($this->pObj->cObj->data['pi_flexform']['data'])) {
			foreach ($this->pObj->cObj->data['pi_flexform']['data'] as $tabKey => $_) {
				$flexConf = tx_mfwcshoolinfos_utils::getFlexformConfigurationFromTab($this->pObj->cObj->data['pi_flexform'], $tabKey, $flexConf);
			}
		}

		// Alle gesammelten Konfigurationen in $this->flex uebertragen.
		foreach ($flexConf as $key => $val) {
			// Alle anderen Konfigurationen...
			$this->pObj->flex = tx_mfwcshoolinfos_utils::setFlexformConfigurationValue($key, $val, $this->pObj->flex);
		}
	}
	
	/**
	 * $data array
	 */
	function doLayout($data){
		exit(json_encode($data));
	}

	
	
	/**
	 * 链接按钮
	 * param $title 链接名称
	 * param $link  链接地址
	 * param $class 按钮样式
	 * param $size 按钮大小 btn-mini btn-large  空值为正常大小
	 * param $doajax boolean 是否是AJAX链接
	 * return string
	 */
	function linkButton($title,$link,$class='icon-list-alt',$size='',$newWindow = FALSE,$doAjax = FALSE){
	
		if($doAjax){
			return '<button onclick="javascript:ajaxLink(jQuery(this));" href="'.$link.'" class="btn '.$size.'" type="button"><i class="'.$class.'"></i> '.$title.'</button>';
		}else if($newWindow){
			return '<button onclick=\'javascript:window.open("'.$link.'","_blank")\' class="btn '.$size.'" type="button"><i class="'.$class.'"></i> '.$title.'</button>';
		}else{
			return '<button onclick=\'javascript:location.href="'.$link.'"\' class="btn '.$size.'" type="button"><i class="'.$class.'"></i> '.$title.'</button>';
		}
	}
	
	/**
	 * 关闭按钮
	 */
	function closeButton(){
		
		return '<button onclick=\'javascript:window.close();\' class="btn btn-danger"><i class="icon-remove icon-white"></i> 关闭</button>';
	}
	
	
	
	/**
	 *  构成typo3的链接 方便 type 等， 自定义形式的构成
	 * self t3 url
	 */
	function selfT3Url($piVars,$altPid,$no_cache=0,$useCacheHash=0,$moreParams=''){
	 
		$urlParameters = Array($this->pObj->prefixId=>$piVars);
		$conf=array();
		$conf['useCacheHash'] = $useCacheHash;
		$conf['no_cache'] = $no_cache;
		$conf['parameter'] = $altPid;
		$conf['additionalParams'] = t3lib_div::implodeArrayForUrl('', $urlParameters, '', TRUE).$moreParams;
		
		$this->pObj->cObj->typoLink('|', $conf);
		$url = $this->pObj->cObj->lastTypoLinkUrl;
		return $url;
	}
	
	/** 
	 * typo3 链接
	 */
	function selfT3UrlWithTitle($title,$piVars,$altPid,$no_cache=0,$useCacheHash=0,$moreParams='',$target = '_blank',$class=''){
		return '<a href="'.$this->selfT3Url($piVars,$altPid,$no_cache,$useCacheHash,$moreParams).'" target="'.$target.'" class="'.$class.'">'.$title.'</a>';
	}
	
	
	/**
	 * 导出 XLS
	 */
	function exportExcel($header, $excelData, $filename) {
	
		require_once(t3lib_extMgm::extPath("phpexcel_library")."sv1/class.tx_phpexcellibrary_sv1.php");
		$PHPExcelSV = t3lib_div::makeInstance("tx_phpexcellibrary_sv1");
		$PHPExcelSV->init();
		$objPHPExcel = new PHPExcel();
		
		$sheet  = $objPHPExcel->setActiveSheetIndex(0); 
		$index = 1;  
		$letter = 'A';
		
		//set column width to 20.
		//保存标题
		foreach($header as $text){
			//$sheet->getColumnDimension($letter)->setWidth(20); 
			$sheet->getStyle(strval($letter).strval($index))->getFont()->setBold(true);
			$sheet->setCellValue(strval($letter).strval($index), $text);
			$letter++;    
		}
		$index++;
		
		//保存数据
		foreach($excelData as $data){
			$letter = 'A';
			foreach(array_keys($header) as $k){
				$text = isset($data[$k])?$data[$k]:'';
				//$sheet->setCellValue(strval($letter).strval($index), $text);
				if(is_numeric($text)){
					$sheet->setCellValue(strval($letter).strval($index),$text);
					$sheet->getStyle(strval($letter).strval($index))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
				}else{
					$sheet->setCellValue(strval($letter).strval($index), ' '.$text);
					//$sheet->setCellValueExplicit(strval($letter).strval($index), $text, PHPExcel_Cell_DataType::TYPE_STRING);
				}
				//$sheet->getStyle(strval($letter).strval($index))->getAlignment()->setWrapText(false); 
				$letter++;
			}
			$index++;
		}
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$filename = iconv('UTF-8', 'GB2312', $filename);
		header('Pragma: public');  
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');  
		header('Content-Type: application/force-download');  
		header('Content-Type: application/vnd.ms-excel');  
		header('Content-Disposition: attachment;filename="' . $filename . '.xls"');  
		header('Cache-Control: max-age=0');  
		$objWriter->save('php://output'); 
		exit;
	}
	
	function encryptPasswordForStorage ($password) {
 
		$encryptedPassword = $password;
		if ($password !== '') {
			if (t3lib_extMgm::isLoaded('saltedpasswords') && tx_saltedpasswords_div::isUsageEnabled('FE')) { //salted password
				$objSalt = tx_saltedpasswords_salts_factory::getSaltingInstance(NULL);
				if (is_object($objSalt)) {
					$encryptedPassword = $objSalt->getHashedPassword($password);
				}
			}
		}
		return $encryptedPassword;
	}
	
	
}
?>